package com.strange.mdl.module.mdl.service.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.strange.mdl.framework.common.enums.CommonStatusEnum;
import com.strange.mdl.module.mdl.mq.producer.user.MdlUserProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.strange.mdl.module.mdl.controller.admin.user.vo.*;
import com.strange.mdl.module.mdl.dal.dataobject.user.MdlUserDO;
import com.strange.mdl.framework.common.pojo.PageResult;
import com.strange.mdl.framework.common.util.object.BeanUtils;

import com.strange.mdl.module.mdl.dal.mysql.user.MdlUserMapper;

import static com.strange.mdl.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.strange.mdl.framework.common.util.collection.CollectionUtils.convertList;
import static com.strange.mdl.framework.common.util.servlet.ServletUtils.getClientIP;
import static com.strange.mdl.module.mdl.enums.ErrorCodeConstants.*;

/**
 * 用户 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class MdlUserServiceImpl implements MdlUserService {

    @Resource
    private MdlUserMapper userMapper;

    @Resource
    private MdlUserProducer memberUserProducer;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Long createUser(MdlUserSaveReqVO createReqVO) {
        // 插入
        MdlUserDO user = BeanUtils.toBean(createReqVO, MdlUserDO.class);
        userMapper.insert(user);
        // 返回
        return user.getId();
    }

    @Override
    public void updateUser(MdlUserSaveReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 更新
        MdlUserDO updateObj = BeanUtils.toBean(updateReqVO, MdlUserDO.class);

        String password = passwordEncoder.encode(updateReqVO.getPassword());
        updateObj.setPassword(password);
        userMapper.updateById(updateObj);
    }

    @Override
    public void deleteUser(Long id) {
        // 校验存在
        validateUserExists(id);
        // 删除
        userMapper.deleteById(id);
    }

    @Override
        public void deleteUserListByIds(List<Long> ids) {
        // 校验存在
        validateUserExists(ids);
        // 删除
        userMapper.deleteByIds(ids);
        }

    @Override
    public MdlUserDO getUser(Long id) {
        return userMapper.selectById(id);
    }


    @Override
    public MdlUserDO getUserByDharmaName(String dharmaName) {
        return userMapper.selectOne("dharma_name", dharmaName);
    }

    private void validateUserExists(List<Long> ids) {
        List<MdlUserDO> list = userMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    private void validateUserExists(Long id) {
        if (userMapper.selectById(id) == null) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public PageResult<MdlUserDO> getUserPage(MdlUserPageReqVO pageReqVO) {
        return userMapper.selectPage(pageReqVO);
    }

    @Override
    public MdlUserDO getUserByMobile(String mobile) {
        return userMapper.selectByMobile(mobile);
    }

    @Override
    public boolean isPasswordMatch(String password, String password1) {
        return passwordEncoder.matches(password, password1);
    }

    @Override
    public void updateUserLogin(Long userId, String clientIP) {

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public MdlUserDO createUserIfAbsent(String mobile, String registerIp, Integer terminal) {
        // 用户已经存在
        MdlUserDO user = userMapper.selectByMobile(mobile);
        if (user != null) {
            return user;
        }
        // 用户不存在，则进行创建
        return createUser(mobile, null, null, registerIp, terminal);
    }
    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }
    private MdlUserDO createUser(String mobile, String nickname, String avtar,
                                    String registerIp, Integer terminal) {
        // 生成密码
        String password = IdUtil.fastSimpleUUID();
        // 插入用户
        MdlUserDO user = new MdlUserDO();
        user.setPhone(mobile);
        user.setIsActive(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
        user.setPassword(encodePassword(password)); // 加密密码
        user.setRegisterIp(registerIp).setRegisterTerminal(terminal);
        user.setDharmaName(nickname).setAvatarUrl(avtar); // 基础信息
        if (StrUtil.isEmpty(nickname)) {
            // 昵称为空时，随机一个名字，避免一些依赖 nickname 的逻辑报错，或者有点丑。例如说，短信发送有昵称时~
            user.setDharmaName("用户" + RandomUtil.randomNumbers(6));
        }
        userMapper.insert(user);

        // 发送 MQ 消息：用户创建
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {

            @Override
            public void afterCommit() {
                memberUserProducer.sendUserCreateMessage(user.getId());
            }

        });
        return user;
    }
}